package com.example.satu.quizcreator.helpers;

import android.content.Context;
import android.os.AsyncTask;

import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.ProgressListener;
import com.dropbox.client2.android.AndroidAuthSession;
import com.dropbox.client2.exception.DropboxException;
import com.example.satu.quizcreator.quiz.Quiz;
import com.example.satu.quizcreator.quiz_chooser.interfaces.onDownloadUploadCompletedListener;
import com.example.satu.quizcreator.quiz_chooser.interfaces.onProgressUpdateListener;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

/**
 * Created by Satu on 2014-12-17.
 */
public class CloudManager {
    private DropboxAPI<AndroidAuthSession> mDBApi;
    Context context;

    public CloudManager(DropboxAPI<AndroidAuthSession> mDBApi, Context context) {
        this.mDBApi = mDBApi;
        this.context = context;
    }

    public ArrayList<String> getItemList (){
        ArrayList<String> strings = null;
        try {
           strings =  new ListAnyncTask().execute().get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return strings;
    }
    public void sendFile (Quiz quiz){
        new UploadAnyncTask().execute(quiz);
    }
    public void download(String fileName){
       /* Quiz quiz = null;*/
        new DownloadAnyncTask().execute(fileName);

/*        return quiz;*/
    }
    class UploadAnyncTask extends AsyncTask<Quiz,Integer,Void> {

        @Override
        protected Void doInBackground(Quiz... params) {
            Quiz quiz = params[0];
            quiz.prepareForUpload();
            File tempFile = null;
            Serializer serializer = new Serializer();
            try {
                tempFile = File.createTempFile(quiz.getName(), "");
                tempFile.deleteOnExit();
                FileOutputStream fos = new FileOutputStream(tempFile);
                // byte[] bytes = ParcelableUtil.marshall(quiz);
                byte[] bytes = serializer.serialize(quiz);
                fos.write(bytes);
                fos.close();

                FileInputStream inputStream = new FileInputStream(tempFile);
                DropboxAPI.Entry response = mDBApi.putFile("/"+quiz.getName(), inputStream,
                        tempFile.length(), null,new ProgressListener() {
                            @Override
                            public void onProgress(long bytes, long total) {
                                publishProgress((int)(100.0*(double)bytes/total));
                            }
                        });
            } catch (IOException e) {
                e.printStackTrace();
            } catch (DropboxException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            if (context instanceof onProgressUpdateListener)
                ((onProgressUpdateListener) context).onUploadProgress(values[0]);
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            if (context instanceof onDownloadUploadCompletedListener)
                ((onDownloadUploadCompletedListener) context).uploadCompleted();
        }
    }

    class ListAnyncTask extends AsyncTask<Void,Void,ArrayList<String>> {
        @Override
        protected ArrayList<String> doInBackground(Void... params) {
            DropboxAPI.Entry entries = null;
            ArrayList<String> strings = new ArrayList<String>();
            try {
                entries = mDBApi.metadata("/", 100, null, true, null);
                for (DropboxAPI.Entry e : entries.contents) {
                    if (!e.isDeleted) {
                        strings.add(e.fileName());
                    }
                }
            } catch (DropboxException e) {
                e.printStackTrace();
            }
            return strings;
        }
    }

    class DownloadAnyncTask extends AsyncTask<String,Integer,Quiz>{
        Quiz quiz = null;
        @Override
        protected Quiz doInBackground(String... params) {
            File file = null;
            Serializer serializer = new Serializer();
            try {
                file = File.createTempFile("temp", "");
                file.deleteOnExit();
                FileOutputStream outputStream = new FileOutputStream(file);
                DropboxAPI.DropboxFileInfo info = mDBApi.getFile("/"+params[0], null, outputStream,new ProgressListener() {
                    @Override
                    public void onProgress(long bytes, long total) {
                        publishProgress((int)(100.0*(double)bytes/total));
                    }
                });
                FileInputStream fileInputStream = new FileInputStream(file);
                byte[] b = new byte[(int) file.length()];
                fileInputStream.read(b);
                quiz = (Quiz) serializer.deserialize(b);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (DropboxException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            return quiz;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            if (context instanceof onProgressUpdateListener)
                ((onProgressUpdateListener) context).onDownloadProgress(values[0]);
        }

        @Override
        protected void onPostExecute(Quiz quiz) {
            super.onPostExecute(quiz);
            if (context instanceof onDownloadUploadCompletedListener)
                ((onDownloadUploadCompletedListener) context).downloadcompleted(quiz);
        }
    }

}
